<?php
date_default_timezone_set("Asia/Shanghai");
session_start();
include_once( 'config.php' );
include_once( 'weibooauth.php' );

$key = getKey();
$client = getHandle($key);
$users = getUsers();

foreach ($users as $user){
	if(!empty($user)){
		$userArr = preg_split("/[\s,]+/", $user);

		$id = $userArr[0];
		$flight = $userArr[1];

		$flightInfo = getFlightInfo($flight);
		if(!strpos($flightInfo[1][2], "--:--")){
			$userInfo = $client->show_user($id);
			$name = $userInfo['name'];
			$planFly = iconv('GB2312', 'UTF-8', $flightInfo[1][0]);
			$actualFly = iconv('GB2312', 'UTF-8', $flightInfo[1][2]);
			$predictLand = iconv('GB2312', 'UTF-8', $flightInfo[1][5]);
			$text = "@".$name." 您监测的航班：".$flight."(".date("Y-m-d").")已经起飞。".$planFly." ".$actualFly." ".$predictLand;
			if(!checkIfExist($text)){
				logTweet($text);
				$client->update($text);
			}
		}
	}
}



function getKey(){
	$fp = fopen("admin/".KEY_FILE, "r");
	$result = fgets($fp);
	$arr = explode(" ", $result);
	$key['token']=$arr[0];
	$key['secret']=$arr[1];
	fclose($fp);
	return $key;
}

function getHandle($key){
	$c = new WeiboClient( WB_AKEY , WB_SKEY , $key['token'] , $key['secret'] );
	return $c;
}

function getUsers(){
	$fp = fopen(RECORD_NAME, "r");
	$info=array();
	while(($buf = fgets($fp))!=false){
		$info[]=$buf;
	}
	fclose($fp);
	return $info;
}

function getFlightInfo($flight){
	$ch = curl_init();
	$options = array(
	CURLOPT_URL=>'http://www.veryzhun.com/searchnum.asp',
	CURLOPT_POST=>true,
	CURLOPT_POSTFIELDS=>'flightnum='.$flight,
	CURLOPT_RETURNTRANSFER=>true
	);
	curl_setopt_array($ch, $options);
	$result = curl_exec($ch);
	$pattern = '/<p>(.*)<\/p>/';
	preg_match_all($pattern, $result, $matches);
	return $matches;
}

function logTweet($text){
	$fp = fopen(TWEETS_LOG, "a");
	$tweet = $text."\n";
	fwrite($fp, $tweet);
	fclose($fp);
}

function checkIfExist($text){
	$exist = false;
	$fp = fopen(TWEETS_LOG, "r");
	$content = fread($fp, filesize(TWEETS_LOG));
	if(strpos($content, $text)!=false){
		$exist = true;
	}
	fclose($fp);
	return $exist;
}